<template>
  <div class="t-m-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchTagVisible" :model="searchForm" inline size="mini" ref="searchForm" @keyup.enter.native="searchTagHandle">
        <el-form-item prop="word" label="标签名称">
          <el-input v-model="searchForm.word" @clear="getTagList" clearable placeholder="请输入标签名称" ></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchTagHandle" type="primary"  icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetTagPageHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="t-tool">
      <el-button :disabled="dataLoad" @click="$refs.tagDialog.initTagDialog(undefined, useStatus)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加标签</el-button>
      <el-button :disabled="dataLoad || tagTableSelected.length === 0" @click="deleteTagHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除标签</el-button>
      <el-popover
        width="500"
        trigger="click"
        @show="showApplyTagHandle"
      >
        <el-table
          v-loading="applyDataLoad"
          element-loading-text="申请标签加载中..."
          element-loading-spinner="el-icon-loading"
          max-height="500"
          :data="applyTagList"
          ref="applyTagTable"
        >
          <el-table-column type="index" header-align="center" align="center" label="序号" width="50"></el-table-column>
          <el-table-column prop="name" header-align="center" align="center" label="标签名字"></el-table-column>
          <el-table-column prop="createTime" header-align="center" align="center" label="申请时间"></el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            width="80"
            label="操作">
            <template v-slot="{ row }">
              <el-button type="text" @click="$refs.auditTagDialog.init(row)">审核</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="applyTableSizeChangeHandle"
          @current-change="applyTableCurrentChangeHandle"
          :current-page="applyTagForm.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="applyTagForm.limit"
          :total="applyTotalNum"
          :disabled="applyDataLoad"
          layout="total, sizes, prev, pager, next, jumper"
          style="float: right;margin: 7px;">
        </el-pagination>
        <el-button type="success" size="mini" plain slot="reference">申请列表</el-button>
      </el-popover>

      <right-tool-bar :search-visible="searchTagVisible" @toggle-search="searchTagVisible = !searchTagVisible"
                      @refresh-table="getTagList" />
    </div>

    <el-table
      v-loading="dataLoad"
      element-loading-text="博客标签加载中..."
      element-loading-spinner="el-icon-loading"
      :data="tagList"
      :default-sort="{ prop: searchForm.field, order: searchForm.order}"
      @sort-change="sortChangeHandle"
      @selection-change="val => this.tagTableSelected = val"
      ref="tagTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="标签名字"></el-table-column>
      <el-table-column prop="sort" sortable :sort-orders="sortOrders" header-align="center" align="center" label="排序等级"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80">
        <template v-slot="scope">
          <el-tag type="info" :class="'m-status' + scope.row.status">
            {{ scope.row.status | baseFormat(statusEnumList)  }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" sortable :sort-orders="sortOrders" header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template v-slot="{ row }">
          <el-button type="text" @click="$refs.tagDialog.initTagDialog(row, undefined)">修改</el-button>
          <el-button v-show="row.status === useStatus" type="text" @click="updateTagStatusHandle(row, disableStatus)">禁用</el-button>
          <el-button v-show="row.status === disableStatus" type="text" @click="updateTagStatusHandle(row, useStatus)">使用</el-button>
          <el-button type="text" @click="deleteTagHandle(row)" class="danger-color">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      :disabled="dataLoad"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 博客标签添加/修改弹出框 -->
    <tag-save-update :status-enum-list="statusEnumList" ref="tagDialog"
                     @close-dialog="closeTagDialogHandle" />

    <!-- 博客标签审核弹出框 -->
    <audit-tag ref="auditTagDialog" @close-dialog="closeAuditTagDialogHandle" />

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import TagSaveUpdate from "@/components/blog/tag/save-update";
  import AuditTag from '@/components/blog/tag/audit'

  export default {
    layout: 'admin',
    name: "admin-tag-manage",
    components: { RightToolBar, TagSaveUpdate, AuditTag },
    data() {
      return {
        // 标签列表
        tagList: [],
        // 标签表格被选中的‘行’数据
        tagTableSelected: [],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 标签检索是否显示
        searchTagVisible: true,
        // 空间检索表单对象
        searchForm: {
          // 标签检索内容
          word: '',
          // 状态[0-可用 1-不可用]
          status: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
          // 排序字段
          field: 'sort',
          // 排序方式
          order: 'ascending'
        },
        // 当前博客数量
        totalNum: 0,
        // 标签弹出框是否显示
        tagDialog: false,
        // 状态枚举列表
        statusEnumList: [],
        // 状态为’可用‘的枚举值
        useStatus: undefined,
        // 状态为’不可用‘的枚举值
        disableStatus: undefined,
        // 申请标签检索对象
        applyTagForm: {
          // 标签检索内容
          word: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
        },
        // 申请标签列表
        applyTagList: [],
        // 申请标签总数
        applyTotalNum: 0,
        // 申请标签数据加载状态[false-不加载 true-加载]
        applyDataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
      }
    },
    // asyncData({ app, params, query}) {
    //   return app.$axios.$post('/blog/tag/list', { page: 1, limit: 10, field: 'sort', order: 'ascending' })
    //     .then(data => {
    //       return {
    //         tagList: data.page.list,
    //         totalNum: data.page.totalNum
    //       }
    //     })
    //     .catch(() => {})
    // },
    filters: {
      /**
       * 枚举映射方法
       * @param {number} value 参数值
       * @param {Array} list  枚举列表
       */
      baseFormat(value, list) {
        for (let obj of list) {
          if (obj.value === value) {
            return obj.name;
          }
        }
        return '未知';
      }
    },
    created() {
      if (process.client) {
        this.getEnumList();
        this.getTagList();
      }
    },
    methods: {
      // 标签检索事件
      searchTagHandle() {
        this.searchForm.page = 1
        this.getTagList()
      },
      /**
       * 获取标签列表方法
       */
      getTagList() {
        // 表格数据加载
        this.dataLoad = true;
        this.$axios.$post('/blog/tag/page/list', this.searchForm)
          .then(({ data:page }) => {
            this.tagList = page.list;
            this.totalNum = page.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 获取申请标签列表方法
       */
      getApplyTagList() {
        // 开始加载
        this.applyDataLoad = true;
        this.$axios.$post('/blog/tag/apply/page/list', this.applyTagForm)
          .then(({ data }) => {
            this.applyTagList = data.data;
            this.applyTotalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 加载结束
            this.applyDataLoad = false;
          })
      },
      /**
       * 获取博客标签枚举数据方法
       */
      getEnumList() {
        this.$axios.$get('/blog/tag/enums')
          .then(({ data }) => {
            this.statusEnumList = data.statusEnumList;
            this.useStatus = data.useStatus;
            this.disableStatus = data.disableStatus;
          })
          .catch(() => {});
      },
      /**
       * 更新博客标签状态事件
       * @param {Object} tag       标签对象
       * @param {number} newStatus 最新状态
       */
      updateTagStatusHandle(tag, newStatus) {
        // 按钮禁用
        this.buttonLoad = true;
        this.$axios.$post('/blog/tag/update/status', { tagId: tag.tagId, status: newStatus })
          .then(() => {
            this.notify('success', '操作成功', `’${tag.name}‘标签状态更新成功`);

            tag.status = newStatus;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          })
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数
       */
      sizeChangeHandle(size) {
        this.searchForm.page = 1
        this.searchForm.limit = size

        this.getTagList()
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        if (this.searchForm.page === index) {
          return
        }
        this.searchForm.page = index
        this.getTagList()
      },
      /**
       * 表格选择字段排序事件
       * @param {string} prop  字段
       * @param {string} order 排序方式
       */
      sortChangeHandle( { prop, order } ) {
        this.searchForm.field = prop
        this.searchForm.order = order

        this.getTagList()
      },
      /**
       * 删除标签事件
       * @param tag 标签对象（只有单个删除时，该参数才有值）
       */
      deleteTagHandle(tag) {
        // 按钮禁用
        this.buttonLoad = true;
        // 所有要删除的标签id
        let tagIds = []
        // 所有要删除的标签名字
        let tagName = "["

        if (tag) {
          tagIds.push(tag.tagId)
          tagName += tag.name
        } else {
          this.tagTableSelected.forEach(tag => {
            tagIds.push(tag.tagId)
            tagName += tag.name + ','
          })
          // 去掉最后一个‘逗号’
          tagName = tagName.substring(0, tagName.length - 1)
        }
        tagName += ']'

        this.$confirm(`确定删除${tagName}标签吗?`, '标签删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return this.$axios.$post('/blog/tag/delete', tagIds);
        })
        .then(() => {
          this.notify('success', '操作成功', `${tagName}标签删除成功`);

          this.getTagList();
        })
        .catch(() => {})
        .finally(() => {
          // 按钮恢复可使用
          this.buttonLoad = false;
        })
      },
      // 关闭标签操作弹出框事件
      closeTagDialogHandle(bool) {
        if (bool) {
          this.getTagList()
        }
      },
      // 重置页面事件
      resetTagPageHandle() {
        // 重置标签查询表单
        this.$refs.searchForm.resetFields()
        this.searchForm.page = 1
      },
      /**
       * 显示申请标签列表事件
       */
      showApplyTagHandle() {
        if (this.applyTagList.length === 0 && this.applyTagForm.page === 1) {
          this.getApplyTagList();
        }
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数
       */
      applyTableSizeChangeHandle(size) {
        this.applyTagForm.page = 1
        this.applyTagForm.limit = size

        this.getApplyTagList()
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      applyTableCurrentChangeHandle(index) {
        if (this.applyTagForm.page === index) {
          return
        }
        this.applyTagForm.page = index
        this.getApplyTagList()
      },
      /**
       * 关闭博客标签审核弹出框事件
       * @param {boolean} refresh 标签申请列表是否刷新[true-刷新 false-不刷新]
       */
      closeAuditTagDialogHandle(refresh) {
        if (refresh) {
          this.getApplyTagList();
        }
      },
    }
  }
</script>

<!--
  css字符对应
  m -> manage
  t -> tag
-->
<style scoped>
  .t-m-page .t-tool {
    margin-bottom: 7px;
  }
  .t-m-page .paging {
    float: right;
    margin: 7px;
  }
  .t-m-page .m-status0 {
    color: #6CBCBC;
  }
  .t-m-page .m-status1 {
    color: #cba457;
  }
</style>
